<template>
  <div class="app-container">
    <el-row>
      <el-input
        size="medium"
        placeholder="帐号、昵称、电话"
        suffix-icon="el-icon-search"
        style="width: 250px"
        v-model="query.s"
        @keyup.enter.native="loadUsers"
      >
      </el-input>

      <el-button type="primary" style="margin-left: 10px;" icon="el-icon-search" @click="loadUsers">搜索</el-button>

      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t("table.add") }}
      </el-button>
    </el-row>

    <el-row>
      <el-table :data="userLs" style="width: 100%" v-loading="loading">
        <el-table-column prop="user.username" label="帐号"> </el-table-column>
        <el-table-column prop="user.nickname" label="昵称"> </el-table-column>
        <el-table-column prop="user.mobile" label="电话"> </el-table-column>
        <el-table-column prop="user.email" label="邮箱"> </el-table-column>

        <el-table-column label="角色">
          <template slot-scope="{ row }">
            <span>{{ roleNames(row.roles) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="所属公司">
          <template slot-scope="{ row }">
            <span>{{ companyNames(row.companies) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态">
          <template slot-scope="{ row }">
            <i v-if="row.user.status > 0" class="el-icon-check" />
          </template>
        </el-table-column>

        <el-table-column prop="user.createTime" label="创建时间">
        </el-table-column>
        <el-table-column prop="user.updateTime" label="修改时间">
        </el-table-column>

        <el-table-column
          :label="$t('table.actions')"
          align="center"
          width="230"
          class-name="fixed-width"
        >
          <template slot-scope="{ row }" v-if="row.user.username != 'root'">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top-end"
            >
              <el-button
                icon="el-icon-edit"
                @click="handlModify(row)"
                circle
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top-end"
            >
              <el-button
                icon="el-icon-delete"
                @click="destory(row)"
                circle
              ></el-button>
            </el-tooltip>

            <el-tooltip
              class="item"
              effect="dark"
              content="密码重置"
              placement="top-end"
            >
              <el-button
                icon="el-icon-refresh-right"
                @click="repasswd(row.user)"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-row>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="query.page"
          :limit.sync="query.size"
          @pagination="loadUsers"
        />
      </el-row>
    </el-row>
    <el-dialog title="编辑单位信息" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tmpModel"
        :close-on-click-modal="false"
        label-position="left"
        label-width="100px"
        style="width: auto; margin-left: 50px"
      >
        <el-form-item label="帐号" prop="user.username">
          <el-input v-model="tmpModel.user.username" />
        </el-form-item>
        <el-form-item v-if="isNew" label="密码" prop="user.password">
          <el-input v-model="tmpModel.user.password" show-password />
        </el-form-item>
        <el-form-item label="昵称" prop="user.nickname">
          <el-input v-model="tmpModel.user.nickname" />
        </el-form-item>
        <el-form-item label="电话" prop="user.mobile">
          <el-input v-model="tmpModel.user.mobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="user.email">
          <el-input v-model="tmpModel.user.email" />
        </el-form-item>
        <el-form-item label="性别" prop="user.gender">
          <el-select v-model="tmpModel.user.gender" placeholder="请选择">
            <el-option
              v-for="item in [
                {
                  label: '未知',
                  value: 0,
                },
                { label: '男', value: 1 },
                { label: '女', value: 2 },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="tmpModel.roles"
            multiple
            collapse-tags
            placeholder="请选择"
          >
            <el-option
              v-for="item in roles"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位类型" prop="companyType">
          <el-radio-group v-model="tmpModel.companyType">
            <el-radio :label="1">独立单位</el-radio>
            <el-radio :label="2">集团单位（待实现）</el-radio>
          </el-radio-group>
          <p style="color: red; weight: bold;margin:0;">
            集团单位用于一个帐号查看多家单位的数据，属于”管理帐号“。数据上传必须使用”独立单位“
          </p>
        </el-form-item>

        <el-form-item label="所属单位" prop="company">
          <el-select
            v-model="tmpModel.company"
            filterable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in companySource"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="tmpModel.user.status"
            >启用/停用</el-checkbox
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="editData">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="dialogFormVisible1">
      <el-form
        ref="dataForm1"
        :rules="rules"
        :model="passwdModel"
        :close-on-click-modal="false"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="密码" prop="passwd">
          <el-input
            v-model="passwdModel.passwd"
            autocomplete="off"
            show-password
          />
        </el-form-item>
        <el-form-item label="重复" prop="passwd1">
          <el-input
            v-model="passwdModel.passwd1"
            autocomplete="off"
            show-password
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="repasswdSubmit">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";

import {
  users,
  roleList,
  compayLs,
  saveUser,
  destoryUser,
  repasswd,
} from "@/api/users";
import { cloneDeep } from "lodash";
import { Form } from "element-ui";
import { parseTime } from "@/utils";
import { use } from "vue/types/umd";
import Pagination from "@/components/Pagination/index.vue";
@Component({
  name: "SysUser",
  components: {
    Pagination,
  },
})
export default class extends Vue {
  mounted() {
    this.loadUsers();
  }
  private created() {
    this.loadCompany();
  }

  private loading: boolean = true;
  private query = {
    page: 1,
    size: 10,
    s: "",
  };
  private total = 0;

  private passwdModel = {
    passwd: "",
    passwd1: "",
    uid: "",
  };
  private dialogFormVisible: boolean = false;
  private dialogFormVisible1: boolean = false;
  private repasswd(user: any) {
    //console.log(user);
    this.dialogFormVisible1 = true;
    this.passwdModel = {
      passwd: "",
      passwd1: "",
      uid: user.userId,
    };
    this.$nextTick(() => {
      (this.$refs.dataForm1 as Form).clearValidate();
    });
  }

  private async repasswdSubmit() {
    (this.$refs.dataForm1 as Form).validate(async (valid) => {
      if (valid) {
        const { data } = await repasswd(this.passwdModel);
        this.passwdModel = {
          passwd: "",
          passwd1: "",
          uid: "",
        };
        this.dialogFormVisible1 = false;
        this.$message({
          message: "操作成功",
          type: "success",
        });
      }
    });
  }
  private defaultModel = {
    user: {
      username: "",
      createTime: parseTime(new Date()),
      updateTime: parseTime(new Date()),
      mobile: "",
      email: "",
      status: 1,
    },
    company: [],
    roles: [],
    companyType: 1,
  };

  private rules = {
    "user.username": [
      {
        required: true,
        message: "不能为空且要保持唯一",
        trigger: "blur",
      },
      { min: 3, max: 30, message: "长度在3到30个字符", trigger: "blur" },
    ],
    "user.nickname": [
      { required: true, message: "名称不能为空", trigger: "blur" },
      { min: 2, max: 10, message: "名称长度在2到10个字符", trigger: "blur" },
    ],
    "user.password": [
      { required: true, message: "不能为空", trigger: "blur" },
      { min: 6, max: 20, message: "长度在6到20个字符", trigger: "blur" },
    ],
    roles: [
      {
        required: true,
        message: "不能为空且",
        trigger: "blur,change",
      },
    ],
    passwd: [
      { required: true, message: "不能为空", trigger: "blur" },
      { min: 6, max: 20, message: "长度在6到20个字符", trigger: "blur" },
    ],
    company: [
      {
        validator: this.comapnyValidator,
        trigger: "blur,change",
      },
    ],
    passwd1: [
      // { required: true, message: "不能为空", trigger: "blur" },
      // { min: 6, max: 20, message: "长度在6到20个字符", trigger: "blur" },
      {
        validator: this.checkPasswd,
        trigger: "blur",
      },
    ],
  };

  private comapnyValidator(row: any, value: any, callback: Function) {
    console.log(this.tmpModel.roles, this.roleLs);

    //独立单位只能属于一个单位，且
    if (this.tmpModel.roles) {
      let ts = this.roleLs.filter(
        (r: any) => this.tmpModel.roles.includes(r.id) && r.code == "DUPLOADER"
      );
      if (ts.length > 0 && this.tmpModel.companyType == 2) {
        callback("”上传数据“的单位只能是”独立单位“");
        return;
      }
    }
    if (this.tmpModel.companyType == 1) {
      if (value && value.length > 1) {
        callback("独立单位只能属于“一个单位”");
        return;
      }
    }
    callback();
  }

  private checkPasswd(role: any, value: any, callback: Function) {
    if (this.passwdModel.passwd != this.passwdModel.passwd1) {
      callback("两次输入的密码不一致！");
    } else callback();
  }

  private tmpModel: any = this.defaultModel;
  private isNew: boolean = false;

  private handleCreate() {
    this.tmpModel = cloneDeep(this.defaultModel);
    this.dialogFormVisible = true;
    this.isNew = true;
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }
  private async handlModify(row: any) {
    let tm = cloneDeep(row);

    if (tm.roles) {
      tm.roles = tm.roles.map((it: any) => it.id);
    }

    if (tm.companies && tm.companies.length > 0) {
      tm.company = tm.companies.map((it: any) => it.id);
    }
    //独立单位：1，集团单位 2
    tm.companyType = tm.company && tm.company.length > 1 ? 2 : 1;
    this.tmpModel = tm;
    this.dialogFormVisible = true;
    this.isNew = false;
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }
  private async destory(row: any) {
    this.$confirm("删除将不可恢复，您确定要删除吗？").then(async (val: any) => {
      let d = await destoryUser([row.user.id]);
      this.loadUsers();
      this.$message({
        message: "删除成功",
        type: "success",
      });
    });
  }
  private editData() {
    (this.$refs.dataForm as Form).validate(async (valid) => {
      if (valid) {
        const model = this.tmpModel;
        this.dialogFormVisible = false;
        this.tmpModel.user.updateTime = parseTime(new Date());
        let user: any = {
          user: this.tmpModel.user,
          roles: this.tmpModel.roles,
        };
        if (this.tmpModel.company) {
          user.companies = this.tmpModel.company;
        }

        const { data } = await saveUser(user);
        this.loadUsers();
        this.$message({
          message: "操作成功",
          type: "success",
        });
      }
    });
  }
  private userLs: Array<any> = [];
  private roleNames(roles: Array<any>) {
    if (roles) {
      return roles.map((it: any) => it.name).join("、");
    }
  }

  private companyNames(companies: Array<any>) {
    if (companies) {
      return companies.map((it: any) => it.name).join("、");
    }
  }

  private roles: Array<any> = [];

  private companySource: Array<any> = [];

  private async loadCompany() {
    //公司列表
    let d: any = await compayLs({ page: 1, size: 10000 });
    d = d.data.content;
    if (d) {
      this.companySource = d.map((it: any) => ({
        label: it.name,
        value: it.id,
      }));
    }
  }
  private roleLs: Array<any> = [];

  private async loadUsers() {
    this.loading = true;
    const { data } = await users(this.query);
    this.userLs = data.ls;
    this.total = data.total;
    this.loading = false;
    //角色列表
    let d: any = await roleList({});
    d = d.data;
    this.roleLs = d;
    this.roles = d
      .filter((it: any) => it.status > 0)
      .map((it: any) => ({ label: it.name, value: it.id }));
  }
}
</script>

<style lang="scss" scoped>
.pagination-container {
  float: right;
}
</style>